package crypt

import (
	"encoding/json"
	"github.com/dgrijalva/jwt-go"
)

// JwtCrypt ...
type JwtCrypt struct {
	key string
}

// SetCryptKey ...
func (c *JwtCrypt) SetCryptKey(key string) error {
	c.key = key
	return nil
}

// ExistCryptKey ...
func (c *JwtCrypt) ExistCryptKey() bool {
	if c.key != "" {
		return true
	}
	return false
}

// Encrypt 加密
func (c *JwtCrypt) Encrypt(data []byte) (string,error) {
	var info jwt.MapClaims
	err := json.Unmarshal(data,&info)
	if err != nil {
		return "", err
	}
	//使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, info)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	return token.SignedString([]byte(c.key))
}

// EncryptWithParams 加密
func (c *JwtCrypt) EncryptWithParams(source interface{}) (string,error) {
	sourceString,err := json.Marshal(source)
	if err !=nil {
		return "", err
	}
	var info jwt.MapClaims
	err = json.Unmarshal(sourceString,&info)
	if err != nil {
		return "", err
	}
	//使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, info)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	return token.SignedString([]byte(c.key))
}


// Decrypt 解密
func (c *JwtCrypt) Decrypt(source string) (interface{},error) {
	temp,err := jwt.Parse(source,  func(tk *jwt.Token) (interface{}, error) {
		return []byte(c.key), nil
	})
	if err != nil {
		return nil, err
	}
	if  !temp.Valid {
		return nil, JwtTokenIsValid
	}
	return temp.Claims, nil
}